import time
from datetime import datetime, timedelta

from flask import abort
from flask import current_app
from flask import g
from flask import redirect
from flask import render_template, jsonify
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info import user_login_data
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.image_storage import storage
from info.utils.response_code import RET

@admin_blu.route('/add_category',methods=["POST"])
def add_category():

    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    if not category_id:
        category = Category()
        category.name = category_name
        db.session.add(category)
    else:
        category = None
        try:
            category_id = int(category_id)
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        if not category:
            return jsonify(errno=RET.NODATA, errmsg="没有找到该分类")

        category.name = category_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK,errmsg="OK")

@admin_blu.route('/get_news_category')
def get_news_category():

    categorys = []
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    categorys_dict_li = []

    for category in categorys:
        categorys_dict_li.append(category.to_dict())

    categorys_dict_li.pop(0)

    return render_template("admin/news_type.html",data={"categorys":categorys_dict_li})

@admin_blu.route('/news_edit_detail',methods=["GET","POST"])
def news_edit_detail():

    if request.method == "GET":

        news_id = request.args.get('news_id')

        if not news_id:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "参数错误"})

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', data={"errmsg": "参数错误"})

        news = None

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', data={"errmsg": "数据查询失败"})

        if not news:
            abort(404)

        categories = []

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', data={"errmsg": "数据查询失败"})

        category_dict_li = []

        for category in categories:
            cate = category.to_dict()
            cate['is_selected'] = False
            if news.category_id == category.id:
                cate['is_selected'] = True

            category_dict_li.append(cate)

        category_dict_li.pop(0)
        print(category_dict_li)

        data={
            "categorys":category_dict_li,
            "news":news.to_dict()
        }

        return render_template("admin/news_edit_detail.html",data=data)


    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 1.1 判断数据是否有值
    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if not news:
        abort(404)

    if index_image:
        try:
            iamge = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="OK")



@admin_blu.route('/news_edit')
def news_edit():

    page = request.args.get('p',1)
    keywords = request.args.get('keywords',"")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []

    total_page = 1
    current_page = 1

    filters = []

    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())

    data={
        "news":news_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }
    return render_template("admin/news_edit.html",data=data)

@admin_blu.route('/news_review_detail',methods=["GET","POST"])
def news_review_detail():

    if request.method == "GET":
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        data = {
            "news":news.to_dict()
        }

        return render_template("admin/news_review_detail.html",data=data)


    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason ')
        news.reason = reason
        news.status = -1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")

@admin_blu.route('/news_review')
def news_review():
    page = request.args.get('p', 1)

    keywords = request.args.get('keywords')

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    news_list = []

    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        total_page = paginate.pages
        current_page = paginate.page
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())

    data = {
        "news": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template("admin/news_review.html", data=data)

@admin_blu.route('/user_list')
def user_list():

    page = request.args.get('p',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    total_page = 1
    current_page = 1
    users = []
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page,constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        total_page = paginate.pages
        current_page = paginate.page
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    users_dict_li = []
    for user in users:
        users_dict_li.append(user.to_admin_dict())

    data={
        "users":users_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }

    return render_template("admin/user_list.html",data=data)

@admin_blu.route('/user_count')
def user_count():
    # 查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
    # 查询月新增数
    mon_count = 0
    now = time.localtime()
    #print("---now----", now)   #---now---- time.struct_time(tm_year=2019, tm_mon=3, tm_mday=5, tm_hour=10, tm_min=57, tm_sec=31, tm_wday=1, tm_yday=64, tm_isdst=0)
    # 得到本月第一天
    mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
    #print("---mon_begin----", mon_begin) #---mon_begin---- 2019-03-01
    # 把第一天的时间转换为字符串
    mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
    #print("---mon_begin_date----", mon_begin_date) # ---mon_begin_date---- 2019-03-01 00:00:00
    try:
        # 查询用户创建时间大于本月第一天的时间
        mon_count = User.query.filter(User.is_admin == False,User.create_time > mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 查询日新增数
    day_count = 0
    # day_begin_date = '%d-%02d-%02d 00:00:00' % (now.tm_year, now.tm_mon, now.tm_mday)
    day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
    day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False,User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 拆线图数据

    active_time = []
    active_count = []

    # 取到今天的时间字符串
    today_date_str = ('%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday))
    # 转成时间对象
    today_date = datetime.strptime(today_date_str, "%Y-%m-%d")

    for i in range(0, 31):
        # 取到今天的0点0分
        begin_date = today_date - timedelta(days=i)
        # 取到昨天的0点0分
        end_date = today_date - timedelta(days=(i - 1))
        # 取出最后一次登录时间大于今天0点的 并且小于昨天凌晨0点的
        count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                  User.last_login < end_date).count()
        active_count.append(count)
        active_time.append(begin_date.strftime('%Y-%m-%d'))

    # User.query.filter(User.is_admin == False, User.last_login >= 今天0点0分, User.last_login < 今天24点).count()

    # 反转，让最近的一天显示在最后
    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_time": active_time,
        "active_count": active_count
    }

    return render_template("admin/user_count.html",data=data)

@admin_blu.route('/index')
@user_login_data
def admin_index():

    user = g.user

    return render_template("admin/index.html",user=user.to_dict())


@admin_blu.route('/login',methods=["GET","POST"])
@user_login_data
def admin_login():
    if request.method == "GET":
        user_id = session.get('user_id',None)
        is_admin = session.get('is_admin',None)

        if user_id and is_admin:
            return redirect(url_for("admin.admin_index"))# 重定向到主界面  地址发生改变 index
        #    return render_template("admin/index.html")  # 返回主界面模板  但是地址还是login
        return render_template("admin/login.html")

    username = request.form.get('username')
    password = request.form.get('password')

    if not all([username,password]):
        return render_template('admin/login.html', errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg="密码错误")

    if not user.is_admin:
        return render_template('admin/login.html', errmsg="权限错误")

    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    session['is_admin'] = True

    return redirect(url_for('admin.admin_index'))

